package cn.dongjak.example.spring.security.service;

import cn.dongjak.example.spring.security.domain.ExampleUser;
import cn.dongjak.example.spring.security.repository.ExampleUserRepository;
import cn.dongjak.example.spring.security.vo.ExampleUserPrincipal;
import com.querydsl.core.types.Predicate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import static cn.dongjak.example.spring.security.domain.QExampleUser.exampleUser;

@Service
public class ExampleUserDetailsService implements UserDetailsService {

    private final ExampleUserRepository userRepository;

    public ExampleUserDetailsService(ExampleUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmailOrPhone) {
        Predicate predicate = exampleUser.username.eq(usernameOrEmailOrPhone)
                .or(exampleUser.email.eq(usernameOrEmailOrPhone))
                .or(exampleUser.phone.eq(usernameOrEmailOrPhone));

        ExampleUser user = userRepository.findOne(predicate).orElseThrow(() -> new UsernameNotFoundException(usernameOrEmailOrPhone));
        return new ExampleUserPrincipal(user);
    }
}